<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">售后详情</h2>
      </div>
      <div class="header-right">
        <el-button v-if="canHandle" type="primary" icon="Edit" @click="openProcessDialog">处理</el-button>
        <el-button v-if="canConfirmRefund" type="success" icon="Money" @click="handleConfirmRefund">确认退款完成</el-button>
        <el-button icon="Printer" @click="handlePrint">打印</el-button>
        <el-button icon="Back" @click="$router.go(-1)">返回</el-button>
      </div>
    </div>

    <div v-loading="loading" class="loading-container">
      <div v-if="!loading && !orderInfo" class="no-data">
        <el-empty description="暂无数据">
          <el-button type="primary" @click="$router.go(-1)">返回</el-button>
        </el-empty>
      </div>

      <div v-if="orderInfo" class="detail-content">
        <!-- 售后单信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">售后单信息</span>
            </div>
          </template>
          <div class="info-grid">
            <div class="info-row">
              <div class="info-item"><label>售后单号</label><span>{{ afterSalesInfo?.afterSalesId || '-' }}</span></div>
              <div class="info-item"><label>关联订单</label><span>{{ afterSalesInfo?.orderId || orderInfo?.orderId || '-' }}</span></div>
              <div class="info-item"><label>售后类型</label><span>{{ formatAfterSalesType(afterSalesInfo?.afterSalesType) }}</span></div>
            </div>
            <div class="info-row">
              <div class="info-item"><label>退款类型</label><span>{{ formatRefundType(afterSalesInfo?.refundType) }}</span></div>
              <div class="info-item"><label>申请时间</label><span>{{ parseTime(afterSalesInfo?.applyTime) || '-' }}</span></div>
              <div class="info-item"><label>退款金额</label><span class="price">{{ afterSalesInfo?.refundPrice ?? '-' }}</span></div>
            </div>
            <div class="info-row">
              <div class="info-item"><label>售后原因</label><span>{{ afterSalesInfo?.afterSalesReason || '-' }}</span></div>
              <div class="info-item"><label>退款原因描述</label><span>{{ afterSalesInfo?.refundReasonDescription || '-' }}</span></div>
              <div class="info-item"><label>退款账户</label><span>{{ afterSalesInfo?.refundAccount || '-' }}</span></div>
            </div>
            <div class="info-row">
              <div class="info-item"><label>处理进度</label><span>{{ afterSalesInfo?.dealPace || '待处理' }}</span></div>
              <div class="info-item"><label>处理结果</label><span>{{ afterSalesInfo?.dealResult || '-' }}</span></div>
              <div class="info-item"><label>退款时间</label><span>{{ parseTime(afterSalesInfo?.refundTime) || '-' }}</span></div>
            </div>
          </div>
        </el-card>

        <!-- 凭证图片 -->
        <el-card v-if="evidenceImages.length" class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">凭证图片</span>
            </div>
          </template>
          <div class="evidence-list">
            <el-image
              v-for="(img, idx) in evidenceImages"
              :key="idx"
              :src="img"
              fit="cover"
              :preview-src-list="evidenceImages"
            />
          </div>
        </el-card>

        <!-- 关联订单信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">关联订单信息</span>
            </div>
          </template>
          <div class="info-grid">
            <div class="info-row">
              <div class="info-item"><label>订单编号</label><span>{{ orderInfo?.platformOrderNo || '-' }}</span></div>
              <div class="info-item"><label>订单状态</label><span>{{ getOrderStatusText(orderInfo?.status) }}</span></div>
              <div class="info-item"><label>商品数量</label><span>{{ orderInfo?.count || '-' }}</span></div>
            </div>
            <div class="info-row">
              <div class="info-item"><label>商品总额</label><span class="price">{{ orderInfo?.platformOrderPrice || '-' }}</span></div>
              <div class="info-item"><label>实付价格</label><span class="price highlight">{{ orderInfo?.realPrice || '-' }}</span></div>
              <div class="info-item"><label>货源地</label><span>{{ orderInfo?.sourcesAddress || '-' }}</span></div>
            </div>
            <div class="info-row">
              <div class="info-item"><label>联系人姓名</label><span>{{ orderInfo?.contactName || '-' }}</span></div>
              <div class="info-item"><label>联系人电话</label><span>{{ orderInfo?.contractTele || '-' }}</span></div>
              <div class="info-item"><label>联系人地址</label><span>{{ orderInfo?.contractAddress || '-' }}</span></div>
            </div>
            <div class="info-row">
              <div class="info-item"><label>支付时间</label><span>{{ parseTime(orderInfo?.payTime) || '-' }}</span></div>
              <div class="info-item"><label>订单创建时间</label><span>{{ parseTime(orderInfo?.orderCreateTime) || '-' }}</span></div>
              <div class="info-item"><label>订单完成时间</label><span>{{ parseTime(orderInfo?.orderCompleteTime) || '-' }}</span></div>
            </div>
            <div class="info-row" v-if="orderInfo?.remark">
              <div class="info-item full-width"><label>用户备注</label><span>{{ orderInfo.remark }}</span></div>
            </div>
          </div>
        </el-card>

        <!-- 商品信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">商品信息</span>
            </div>
          </template>
          <div class="goods-table">
            <el-table :data="goodsList" border>
              <el-table-column label="商品主图" align="center" width="100">
                <template #default="scope">
                  <div class="goods-image">
                    <el-image :src="(scope.row.goodsImage || scope.row.GoodsImage || scope.row.image) || '/default-product.png'" fit="cover" :preview-src-list="(scope.row.goodsImage || scope.row.GoodsImage || scope.row.image) ? [scope.row.goodsImage || scope.row.GoodsImage || scope.row.image] : []" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品名称" prop="goodName" align="center" min-width="150" />
              <el-table-column label="商品规格" prop="goodSize" align="center" width="120" />
              <el-table-column label="商品单价" prop="price" align="center" width="100">
                <template #default="scope">
                  <span class="price">{{ scope.row.price || orderInfo?.goodPrice || orderInfo?.platformOrderPrice || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="购买数量" prop="count" align="center" width="100" />
              <el-table-column label="小计" align="center" width="120">
                <template #default="scope">
                  <span class="price">{{ (scope.row.price || 0) * (scope.row.count || 1) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="售后处理" width="560px" :close-on-click-modal="false">
      <el-form ref="processFormRef" :model="processForm" :rules="processRules" label-width="110px">
        <el-form-item label="处理结论" prop="decisionType">
          <el-select v-model="processForm.decisionType" placeholder="请选择">
            <el-option label="全额退款" value="agree_full" />
            <el-option label="部分退款" value="agree_partial" />
            <el-option label="不同意退款" value="reject" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="['agree_full','agree_partial'].includes(processForm.decisionType)" label="退款金额" prop="refundAmount">
          <el-input-number v-model="processForm.refundAmount" :min="0" :max="Number(orderInfo?.realPrice || 0)" :precision="2" :step="1" :disabled="processForm.decisionType==='agree_full'" />
          <span class="amount-tip">（最大可退 {{ orderInfo?.realPrice || 0 }} ）</span>
        </el-form-item>
        <el-form-item v-if="processForm.decisionType==='reject'" label="拒绝原因" prop="rejectReason">
          <el-input v-model="processForm.rejectReason" type="textarea" :rows="3" placeholder="请输入拒绝原因" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="处理意见">
          <el-input v-model="processForm.opinion" type="textarea" :rows="3" placeholder="可填写补充说明（选填）" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleProcessConfirm" :loading="processLoading">确认处理</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import { listAfterSales, updateAfterSales } from '@/api/order/afterSales'

// 订单与售后数据
const loading = ref(true)
const route = useRoute()
const orderInfo = ref(null)
const goodsList = ref([])
const afterSalesList = ref([])
const afterSalesInfo = ref(null)

// UI 状态
const processDialogVisible = ref(false)
const processFormRef = ref(null)
const processLoading = ref(false)
const processForm = ref({
  decisionType: 'agree_full',
  refundAmount: 0,
  opinion: '',
  rejectReason: ''
})
const processRules = {
  decisionType: [{ required: true, message: '请选择处理结论', trigger: 'change' }],
  refundAmount: [
    {
      validator: (rule, value, callback) => {
        if (!['agree_full', 'agree_partial'].includes(processForm.value.decisionType)) return callback()
        const max = Number(orderInfo.value?.realPrice || 0)
        if (processForm.value.decisionType === 'agree_full') {
          if (value === undefined || value === null) return callback(new Error('金额有误'))
          if (Number(value) !== max) return callback(new Error('全额退款金额必须等于实付金额'))
        } else {
          if (!value || Number(value) <= 0) return callback(new Error('请输入退款金额'))
          if (Number(value) > max) return callback(new Error('退款金额不能超过实付金额'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  rejectReason: [
    {
      validator: (rule, value, callback) => {
        if (processForm.value.decisionType === 'reject' && !value) {
          return callback(new Error('请输入拒绝原因'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性与权限控制
const evidenceImages = computed(() => {
  const imgs = afterSalesInfo.value?.evidenceImages
  if (!imgs) return []
  return Array.isArray(imgs) ? imgs : String(imgs).split(',').filter(Boolean)
})

const canHandle = computed(() => {
  const s = afterSalesInfo.value?.dealPace || '待处理'
  return !['已完成', '已取消', '已退款'].includes(s)
})
const canConfirmRefund = computed(() => afterSalesInfo.value && afterSalesInfo.value.dealPace === '已同意退款' && !afterSalesInfo.value.refundTime)

// 生命周期：解析路由、加载售后记录
onMounted(async () => {
  try {
    if (route.query.orderData) {
      const data = JSON.parse(route.query.orderData)
      orderInfo.value = Array.isArray(data) ? data[0] : data
      if (orderInfo.value?.goodDetils && Array.isArray(orderInfo.value.goodDetils)) {
        goodsList.value = orderInfo.value.goodDetils
      } else {
        goodsList.value = [
          {
            goodName: orderInfo.value?.platformOrderDesc || '商品',
            goodSize: '默认规格',
            price: orderInfo.value?.goodPrice || orderInfo.value?.platformOrderPrice,
            count: orderInfo.value?.count || 1,
            GoodsImage: null
          }
        ]
      }
    }

    const resp = await listAfterSales()
    afterSalesList.value = resp?.rows || []
    const matched = afterSalesList.value.filter((it) => String(it.orderId) === String(orderInfo.value?.orderId))
    afterSalesInfo.value = matched.length ? matched[0] : null
  } catch (e) {
    console.error('加载售后详情失败: ', e)
  } finally {
    loading.value = false
  }
})

// 格式化函数
function getOrderStatusText(status) {
  const map = { 1: '待支付', 2: '待发货', 3: '已发货', 4: '已完成', 5: '已取消', 6: '售后处理' }
  return map[status] || '-'
}

function formatAfterSalesType(t) {
  const map = { 1: '未支付订单', 2: '已支付订单' }
  return map?.[t] || '-'
}

function formatRefundType(t) {
  const map = { 1: '全部退款', 2: '部分退款' }
  return map?.[t] || '-'
}

// 业务动作
function openProcessDialog() {
  // 初始化表单
  processForm.value.decisionType = 'agree_full'
  processForm.value.refundAmount = Number(orderInfo.value?.realPrice || 0)
  processForm.value.opinion = ''
  processForm.value.rejectReason = ''
  processDialogVisible.value = true
}

watch(
  () => processForm.value.decisionType,
  (v) => {
    if (v === 'agree_full') {
      processForm.value.refundAmount = Number(orderInfo.value?.realPrice || 0)
    } else if (v === 'agree_partial') {
      processForm.value.refundAmount = undefined
    } else {
      processForm.value.refundAmount = 0
    }
  }
)

async function handleProcessConfirm() {
  if (!processFormRef.value || !afterSalesInfo.value) return
  try {
    const valid = await processFormRef.value.validate()
    if (!valid) return
    processLoading.value = true

    let payload = { ...afterSalesInfo.value }
    if (processForm.value.decisionType === 'agree_full') {
      payload.dealPace = '已同意退款'
      payload.dealResult = `全额退款；${processForm.value.opinion || ''}`.trim()
      payload.refundType = 1
      payload.refundPrice = Number(orderInfo.value?.realPrice || 0)
    } else if (processForm.value.decisionType === 'agree_partial') {
      payload.dealPace = '已同意退款'
      payload.dealResult = `部分退款 ${Number(processForm.value.refundAmount).toFixed(2)}；${processForm.value.opinion || ''}`.trim()
      payload.refundType = 2
      payload.refundPrice = Number(processForm.value.refundAmount)
    } else {
      payload.dealPace = '已拒绝'
      payload.dealResult = `拒绝退款；${processForm.value.rejectReason}`.trim()
      payload.refundType = null
      payload.refundPrice = 0
    }

    await updateAfterSales(payload)
    // 同步本地数据
    afterSalesInfo.value = { ...afterSalesInfo.value, ...payload }
    processDialogVisible.value = false
    ElMessage.success('处理成功')
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('处理失败')
  } finally {
    processLoading.value = false
  }
}

async function handleConfirmRefund() {
  if (!afterSalesInfo.value) return
  try {
    await ElMessageBox.confirm('确认已经完成退款并入账？', '提示', { type: 'warning' })
    const now = new Date()
    const payload = { ...afterSalesInfo.value, dealPace: '退款完成', dealResult: '退款完成', refundTime: now }
    await updateAfterSales(payload)
    afterSalesInfo.value.dealPace = '退款完成'
    afterSalesInfo.value.dealResult = '退款完成'
    afterSalesInfo.value.refundTime = now
    ElMessage.success('已确认退款完成')
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('操作失败')
  }
}

function handlePrint() {
  window.print()
}
</script>

<style scoped lang="scss">
.app-container { padding: 20px; }

.page-header {
  display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #e4e7ed;
  .page-title { margin: 0; font-size: 24px; font-weight: 600; color: #303133; }
  .header-right { display: flex; gap: 12px; }
}

.detail-card { margin-bottom: 20px; border: 1px solid #e4e7ed; border-radius: 8px; }
.card-header { .card-title { font-size: 16px; font-weight: 600; color: #303133; } }

.info-grid {
  border: 1px solid #e4e7ed; border-radius: 4px;
  .info-row { display: flex; border-bottom: 1px solid #e4e7ed; &:last-child { border-bottom: none; }
    .info-item { flex: 1; display: flex; align-items: center; min-height: 48px; padding: 12px 16px; border-right: 1px solid #e4e7ed;
      &:last-child { border-right: none; }
      &.full-width { flex: 3; border-right: none; }
      label { display: inline-block; min-width: 120px; font-weight: 500; color: #303133; text-align: center; background-color: #f5f7fa; padding: 12px 8px; border-right: 1px solid #e4e7ed; margin: -12px 12px -12px -16px; }
      span { color: #303133; flex: 1; word-break: break-all; &.price { font-weight: 600; color: #f56c6c; &.highlight { font-size: 18px; color: #e6a23c; } } }
    }
  }
}

.evidence-list { display: flex; flex-wrap: wrap; gap: 12px; .el-image { width: 100px; height: 100px; border: 1px solid #e4e7ed; border-radius: 6px; } }

.goods-table :deep(.el-table) {
  .goods-image { width: 60px; height: 60px; border-radius: 6px; overflow: hidden; border: 1px solid #e4e7ed; margin: 0 auto;
    .el-image { width: 100%; height: 100%; }
  }
  .price { font-weight: 600; color: #f56c6c; }
  .el-table__row { height: 80px; }
  .el-table__cell { padding: 8px 0; vertical-align: middle; }
}

.no-data { text-align: center; padding: 60px 20px; }

@media print { .page-header .header-right { display: none; } }
</style>